<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第一章：熟悉 Objective-C 语言第1条：了解 Objective-C 语言的起源消息结构Objective-C 使用的是“消息结构”（messaging structure）而非“函数调用”（function calling）。使用消息结构的语言，其运行时所执行的代码由运行环境决定。而使用函数调用的语言，则由编译器决定。    在C&#x2F;C++中，如果使用的函数是多态，那么运行时会">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第一章阅读笔记">
<meta property="og:url" content="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第一章：熟悉 Objective-C 语言第1条：了解 Objective-C 语言的起源消息结构Objective-C 使用的是“消息结构”（messaging structure）而非“函数调用”（function calling）。使用消息结构的语言，其运行时所执行的代码由运行环境决定。而使用函数调用的语言，则由编译器决定。    在C&#x2F;C++中，如果使用的函数是多态，那么运行时会">
<meta property="og:locale">
<meta property="article:published_time" content="2018-04-12T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:14:08.057Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/","path":"2018/04/2018/04/《Effective Objective-C 2.0》第一章阅读笔记/","title":"《Effective Objective-C 2.0》第一章阅读笔记"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第一章阅读笔记 | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E7%86%9F%E6%82%89-Objective-C-%E8%AF%AD%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">第一章：熟悉 Objective-C 语言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC1%E6%9D%A1%EF%BC%9A%E4%BA%86%E8%A7%A3-Objective-C-%E8%AF%AD%E8%A8%80%E7%9A%84%E8%B5%B7%E6%BA%90"><span class="nav-number">1.1.</span> <span class="nav-text">第1条：了解 Objective-C 语言的起源</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E7%BB%93%E6%9E%84"><span class="nav-number">1.1.0.1.</span> <span class="nav-text">消息结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%90%E8%A1%8C%E6%9C%9F%E7%BB%84%E4%BB%B6%EF%BC%88runtime-component%EF%BC%89"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">运行期组件（runtime component）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D"><span class="nav-number">1.1.0.3.</span> <span class="nav-text">对象内存分配</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC2%E6%9D%A1%EF%BC%9A%E5%9C%A8%E7%B1%BB%E7%9A%84%E5%A4%B4%E6%96%87%E4%BB%B6%E4%B8%AD%E5%B0%BD%E9%87%8F%E5%B0%91%E5%BC%95%E7%94%A8%E5%85%B6%E4%BB%96%E5%A4%B4%E6%96%87%E4%BB%B6"><span class="nav-number">1.2.</span> <span class="nav-text">第2条：在类的头文件中尽量少引用其他头文件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%90%91%E5%89%8D%E5%A3%B0%E6%98%8E%EF%BC%88forward-declaring%EF%BC%89"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">向前声明（forward declaring）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">循环引用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A4%B4%E6%96%87%E4%BB%B6%E9%9C%80%E8%A6%81%E5%BC%95%E7%94%A8%E5%8D%8F%E8%AE%AE"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">头文件需要引用协议</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC3%E6%9D%A1%EF%BC%9A%E5%A4%9A%E7%94%A8%E5%AD%97%E9%9D%A2%E9%87%8F%E8%AF%AD%E6%B3%95%EF%BC%8C%E5%B0%91%E7%94%A8%E4%B8%8E%E4%B9%8B%E7%AD%89%E4%BB%B7%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-number">1.3.</span> <span class="nav-text">第3条：多用字面量语法，少用与之等价的方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC4%E6%9D%A1%EF%BC%9A%E5%A4%9A%E7%94%A8%E7%B1%BB%E5%9E%8B%E5%B8%B8%E9%87%8F%EF%BC%8C%E5%B0%91%E7%94%A8-define-%E9%A2%84%E5%A4%84%E7%90%86%E6%8C%87%E4%BB%A4"><span class="nav-number">1.4.</span> <span class="nav-text">第4条：多用类型常量，少用 #define 预处理指令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-define-%E6%97%A0%E6%B3%95%E7%A1%AE%E5%AE%9A%E7%B1%BB%E5%9E%8B%E4%BF%A1%E6%81%AF"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">使用 #define 无法确定类型信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#static-const-%E4%BF%AE%E9%A5%B0"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">static const 修饰</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#extern-%E5%A3%B0%E6%98%8E%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="nav-number">1.4.0.3.</span> <span class="nav-text">extern 声明全局变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%A4%E6%96%AD-const-%E4%BF%AE%E9%A5%B0%E7%9A%84%E6%98%AF%E5%AF%B9%E8%B1%A1%E8%BF%98%E6%98%AF%E6%8C%87%E9%92%88-%E8%87%AA%E5%B7%B1%E7%90%86%E8%A7%A3"><span class="nav-number">1.4.0.4.</span> <span class="nav-text">判断 const 修饰的是对象还是指针(自己理解)</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC5%E6%9D%A1%EF%BC%9A%E7%94%A8%E6%9E%9A%E4%B8%BE%E8%A1%A8%E7%A4%BA%E7%8A%B6%E6%80%81%E3%80%81%E9%80%89%E9%A1%B9%E3%80%81%E7%8A%B6%E6%80%81%E7%A0%81"><span class="nav-number">1.5.</span> <span class="nav-text">第5条：用枚举表示状态、选项、状态码</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F"><span class="nav-number">1.5.0.1.</span> <span class="nav-text">注意</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第一章阅读笔记 | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第一章阅读笔记
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-13 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-13T00:00:00+08:00">2018-04-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:14:08" itemprop="dateModified" datetime="2018-07-01T16:14:08+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第一章：熟悉-Objective-C-语言"><a href="#第一章：熟悉-Objective-C-语言" class="headerlink" title="第一章：熟悉 Objective-C 语言"></a><center>第一章：熟悉 Objective-C 语言</center></h1><h2 id="第1条：了解-Objective-C-语言的起源"><a href="#第1条：了解-Objective-C-语言的起源" class="headerlink" title="第1条：了解 Objective-C 语言的起源"></a>第1条：了解 Objective-C 语言的起源</h2><h4 id="消息结构"><a href="#消息结构" class="headerlink" title="消息结构"></a>消息结构</h4><p>Objective-C 使用的是“消息结构”（messaging structure）而非“函数调用”（function calling）。<br>使用消息结构的语言，其运行时所执行的代码由运行环境决定。而使用函数调用的语言，则由编译器决定。  </p>
<blockquote>
<p>在C&#x2F;C++中，如果使用的函数是多态，那么运行时会根据“虚方法表”（virtual table）来查找应该执行哪个函数实现。而采用消息结构的语言则都是在运行的时候才查找要执行的方法。</p>
</blockquote>
<h4 id="运行期组件（runtime-component）"><a href="#运行期组件（runtime-component）" class="headerlink" title="运行期组件（runtime component）"></a>运行期组件（runtime component）</h4><p>Objective-C 中重要工作都由运行期组件完成，而非编译器。里面包含了面向对象所需的全部数据结构及函数。其本质是与开发者所编写的代码相链接的动态库。</p>
<h4 id="对象内存分配"><a href="#对象内存分配" class="headerlink" title="对象内存分配"></a>对象内存分配</h4><p>对象所占有的内存总是分配到堆空间（Head）中，而指向对象的指针则是分配到栈（stack）中。分配到堆中的内存必须进行管理，分配到栈上用于保存对象地址的内存，则会在栈帧弹出时自动处理。<br>当遇到非指针类型变量的时候，变量可能会分配到栈空间，比如：结构体。</p>
<h2 id="第2条：在类的头文件中尽量少引用其他头文件"><a href="#第2条：在类的头文件中尽量少引用其他头文件" class="headerlink" title="第2条：在类的头文件中尽量少引用其他头文件"></a>第2条：在类的头文件中尽量少引用其他头文件</h2><h4 id="向前声明（forward-declaring）"><a href="#向前声明（forward-declaring）" class="headerlink" title="向前声明（forward declaring）"></a>向前声明（forward declaring）</h4><p>如果只需要知道有那么一个类名，则不需要引用该类名的头文件（不需要知道其他细节），这时可以向前声明该类，既使用：</p>
<blockquote>
<p>@class className;  </p>
</blockquote>
<p>然后在实现文件中引入该头文件。这样可以降低类与类之间的耦合。<br>引入头文件的时机应该尽量延后，只有当确定要引用该头文件的时候才引用。将大量的头文件引入到头文件中，会增加文件之间的依赖性，从而增加编译时间。   </p>
<h4 id="循环引用"><a href="#循环引用" class="headerlink" title="循环引用"></a>循环引用</h4><p>向前申明可以解决两个类之间的循环引用。文章说道：</p>
<blockquote>
<p>使用 #import 虽然不会导致引用循环，但却意味着两个类有一个不能被正确编译。</p>
</blockquote>
<p>不过，这句话我。。。。无法理解！！！  </p>
<h4 id="头文件需要引用协议"><a href="#头文件需要引用协议" class="headerlink" title="头文件需要引用协议"></a>头文件需要引用协议</h4><p>如果要使用某个协议，则不能使用向前声明，为了不引用整个头文件，可以将协议放到“class-continuation 分类”中，或者单独放到一个文件中，然后使用 #import 引用头文件，这样就不会出现上面说的问题。</p>
<h2 id="第3条：多用字面量语法，少用与之等价的方法"><a href="#第3条：多用字面量语法，少用与之等价的方法" class="headerlink" title="第3条：多用字面量语法，少用与之等价的方法"></a>第3条：多用字面量语法，少用与之等价的方法</h2><p>使用字面量语法可以缩减代码长度，提高代码可读性。也要确保创建对象的时候不能为nil。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSString</span> *string0 = [[<span class="built_in">NSString</span> alloc] initWithString:<span class="string">@&quot;123&quot;</span>];</span><br><span class="line"><span class="built_in">NSString</span> *string1 = <span class="string">@&quot;123&quot;</span>;</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSNumber</span> *number0 = [<span class="built_in">NSNumber</span> numberWithInt:<span class="number">1</span>];</span><br><span class="line"><span class="built_in">NSNumber</span> *number1 = @<span class="number">1</span>;</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSArray</span> *array0 = [<span class="built_in">NSArray</span> arrayWithObjects:<span class="string">@&quot;cat&quot;</span>, <span class="string">@&quot;dog&quot;</span>, <span class="string">@&quot;fish&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSString</span> *cat0 = [array0 objectAtIndex:<span class="number">0</span>];</span><br><span class="line"><span class="built_in">NSArray</span> *array1 = @[<span class="string">@&quot;cat&quot;</span>, <span class="string">@&quot;dog&quot;</span>, <span class="string">@&quot;fish&quot;</span>];</span><br><span class="line"><span class="built_in">NSString</span> *cat1 = array1[<span class="number">0</span>];</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSDictionary</span> *dictionary0 = [<span class="built_in">NSDictionary</span> dictionaryWithObjectsAndKeys:<span class="string">@&quot;key0&quot;</span>, <span class="string">@&quot;value0&quot;</span>, <span class="string">@&quot;key1&quot;</span>, <span class="string">@&quot;value1&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSString</span> *value0 = [dictionary0 objectForKey:<span class="string">@&quot;key0&quot;</span>];</span><br><span class="line">	</span><br><span class="line"><span class="built_in">NSDictionary</span> *dictionary1 = @&#123;<span class="string">@&quot;key0&quot;</span>:<span class="string">@&quot;value0&quot;</span>, <span class="string">@&quot;key1&quot;</span>:<span class="string">@&quot;value1&quot;</span>&#125;;</span><br><span class="line"><span class="built_in">NSString</span> *value1 = dictionary1[<span class="string">@&quot;key1&quot;</span>];</span><br></pre></td></tr></table></figure>

<h2 id="第4条：多用类型常量，少用-define-预处理指令"><a href="#第4条：多用类型常量，少用-define-预处理指令" class="headerlink" title="第4条：多用类型常量，少用 #define 预处理指令"></a>第4条：多用类型常量，少用 #define 预处理指令</h2><h4 id="使用-define-无法确定类型信息"><a href="#使用-define-无法确定类型信息" class="headerlink" title="使用 #define 无法确定类型信息"></a>使用 #define 无法确定类型信息</h4><p>比如下面的代码用 #define 无法预知 kAnimationDuration 的数据类型，不利于编写开发文档。   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> kAnimationDuration 0.1</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="built_in">NSTimeInterval</span> kAnimationDuration = <span class="number">0.1</span>;</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="type">float</span> kAnimationDuration = <span class="number">0.1</span>;</span><br></pre></td></tr></table></figure>

<h4 id="static-const-修饰"><a href="#static-const-修饰" class="headerlink" title="static const 修饰"></a>static const 修饰</h4><p>如果一个变量用 static const 修饰，那么编译器不会创建符号，而是会像 #define 预处理指令一样，在编译的时候将所有的变量替换成常值。</p>
<h4 id="extern-声明全局变量"><a href="#extern-声明全局变量" class="headerlink" title="extern 声明全局变量"></a>extern 声明全局变量</h4><p>使用 static const 修饰的变量只能在本文件内使用，但有时候需要对外公布这个变量，比如该变量作为“通知”的key的时候，此时可以稍微改一下。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// .h文件 声明一个变量</span></span><br><span class="line"><span class="keyword">extern</span> <span class="built_in">NSString</span> *<span class="keyword">const</span> VCHLoginNotification;</span><br><span class="line"><span class="comment">// .m文件 定义一个变量</span></span><br><span class="line"><span class="built_in">NSString</span> *<span class="keyword">const</span> VCHLoginNotification = <span class="string">@&quot;kLoginNotification&quot;</span>;</span><br></pre></td></tr></table></figure>
<p>这种变量会保存在“全局符号表”中。为了避免命名冲突，这种变量应该加上类名前缀。</p>
<h4 id="判断-const-修饰的是对象还是指针-自己理解"><a href="#判断-const-修饰的是对象还是指针-自己理解" class="headerlink" title="判断 const 修饰的是对象还是指针(自己理解)"></a>判断 const 修饰的是对象还是指针(自己理解)</h4><p>const 修饰的是右边的第一个字符  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">float</span> <span class="keyword">const</span> valueFloat0 = <span class="number">0.1</span>; <span class="comment">//[1]</span></span><br><span class="line"><span class="keyword">const</span> <span class="type">float</span> valueFloat1 = <span class="number">0.1</span>; <span class="comment">//[2]</span></span><br><span class="line"><span class="built_in">NSString</span> <span class="keyword">const</span> * string0 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[3]</span></span><br><span class="line"><span class="built_in">NSString</span> * <span class="keyword">const</span> string1 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[4]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> * string2 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[5]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> * <span class="keyword">const</span> string3 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[6]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> <span class="keyword">const</span> * string4 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[7]</span></span><br></pre></td></tr></table></figure>
<p>[1] const 右边第一个字符是 valueFloat0，表示 valueFloat0 里面的值是不变的。valueFloat0  不能是左值。<br>[2] const 右边第一个字符是 float，而 float 指的就是 valueFloat1，所以 valueFloat1 的值是不变的。valueFloat1 不能是左值。<br>[3] const 右边第一个字符是 string0，string0 是一个指针，所以 string0 指向的地址是不变的。string0 不能是左值。<br>[4] const 右边第一个字符是 string1（指针），所以 string1 指向的地址是不变的。string1 不能是左值。<br>[5] const 右边第一个字符是 NSString，表示的是 @”abc” 这个对象，所以 @”abc 是不可变对象。不可以通过 string2 这个指针来修改它指向的对象的内容。(这里刚好 @”abc” 是不能修改的，就算指向的对象是可以被修改的，也不能通过 const 修饰的指针去修改)<br>[6] 第一个 const 右边第一个字符是 NSString， 等同于 [5]。第二个 const 等同于 [4]。<br>[7] 等同于 [6]  </p>
<h2 id="第5条：用枚举表示状态、选项、状态码"><a href="#第5条：用枚举表示状态、选项、状态码" class="headerlink" title="第5条：用枚举表示状态、选项、状态码"></a>第5条：用枚举表示状态、选项、状态码</h2><p>枚举可以提高代码可读性。   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 状态、状态码</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">NS_ENUM</span>(<span class="built_in">NSInteger</span>, <span class="built_in">UIViewAnimationTransition</span>) &#123;</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionNone</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionFlipFromLeft</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionFlipFromRight</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionCurlUp</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionCurlDown</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 可组合选项</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">NS_OPTIONS</span>(<span class="built_in">NSUInteger</span>, <span class="built_in">UIViewAutoresizing</span>) &#123;</span><br><span class="line">    <span class="built_in">UIViewAutoresizingNone</span>                 = <span class="number">0</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleLeftMargin</span>   = <span class="number">1</span> &lt;&lt; <span class="number">0</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleWidth</span>        = <span class="number">1</span> &lt;&lt; <span class="number">1</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleRightMargin</span>  = <span class="number">1</span> &lt;&lt; <span class="number">2</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleTopMargin</span>    = <span class="number">1</span> &lt;&lt; <span class="number">3</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleHeight</span>       = <span class="number">1</span> &lt;&lt; <span class="number">4</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleBottomMargin</span> = <span class="number">1</span> &lt;&lt; <span class="number">5</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>enum 用来表示状态，options 用来表示可组合的选项。</p>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>1、用枚举处理 switch 的时候不要实现 default 分支。这样加入新的分支后，编译器就会提示开发者。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BC%96%E8%AF%91%E6%97%B6%E4%B8%8E%E8%BF%90%E8%A1%8C%E6%97%B6/" rel="prev" title="iOS基础之编译时与运行时">
                  <i class="fa fa-chevron-left"></i> iOS基础之编译时与运行时
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/" rel="next" title="《Effective Objective-C 2.0》第二章阅读笔记(1)">
                  《Effective Objective-C 2.0》第二章阅读笔记(1) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
